package com.example.loginpilot_01.service.announcement;

import com.example.loginpilot_01.entity.Announcement;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class AnnouncementService {

    private final AnnouncementRepository announcementRepository;

    // 构造方法注入
    public AnnouncementService(AnnouncementRepository announcementRepository) {
        this.announcementRepository = announcementRepository;
    }

    // 1. 发布公告
    public void publishAnnouncement(Announcement announcement, String publisher) {
        announcement.setPublisher(publisher); // 设置发布人（当前登录管理员用户名）
        announcement.setPublishTime(new Date()); // 设置发布时间（当前时间）
        announcementRepository.save(announcement);
    }

    // 2. 编辑公告（根据ID更新）
    public void updateAnnouncement(Announcement announcement) {
        Announcement existing = announcementRepository.findById(announcement.getId())
                .orElseThrow(() -> new RuntimeException("公告不存在"));
        // 只更新标题、内容、是否置顶（发布人、发布时间不变）
        existing.setTitle(announcement.getTitle());
        existing.setContent(announcement.getContent());
        existing.setIsTop(announcement.getIsTop());
        announcementRepository.save(existing);
    }

    // 3. 删除公告（根据ID）
    public void deleteAnnouncement(Integer id) {
        announcementRepository.deleteById(id);
    }

    // 4. 查询所有公告（按置顶+时间排序）
    public List<Announcement> getAllAnnouncements() {
        return announcementRepository.findAllByOrderByIsTopDescPublishTimeDesc();
    }

    // 5. 根据ID查询公告（用于编辑/查看详情）
    public Announcement getAnnouncementById(Integer id) {
        return announcementRepository.findById(id).orElse(null);
    }
}